package com.mallbook.controller.servlet.front;

import com.alibaba.fastjson.JSON;
import com.mallbook.model.exception.AddressDefaultNumMuchException;
import com.mallbook.model.exception.AddressNumMuchException;
import com.mallbook.model.exception.ServiceException;
import com.mallbook.model.pojo.Address;
import com.mallbook.model.pojo.Region;
import com.mallbook.model.pojo.User;
import com.mallbook.model.service.AddressService;
import com.mallbook.model.service.RegionService;
import com.mallbook.model.utils.MallDefaultConfig;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

/**
 * @Author 宋明松
 * @Version V1.0.0
 * @Date 2022-07-17
 */
@WebServlet("/ucenter/address")
public class AddressServlet extends HttpServlet {
    private static final Logger logger = LoggerFactory.getLogger(UserServlet.class);
    private AddressService addressService = new AddressService();
    private RegionService regionService = new RegionService();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html");
        resp.setCharacterEncoding("utf-8");
        req.setCharacterEncoding("utf-8");
        String opr = req.getParameter("opr");
        switch (opr) {
            case "list":
                doList(req, resp);
                break;
            case "province":
                doProvince(req, resp);
                break;
            case "add":
                doAdd(req, resp);
                break;
            case "initupdate":
                doInitupdate(req, resp);
                break;
            case "update":
                doUpdate(req, resp);
                break;
            case "setdefault":
                doSetDefault(req, resp);
                break;
            case "del":
                doDel(req, resp);
                break;

        }
    }

    private void doUpdate(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
        String id = req.getParameter("id");
        String accept = req.getParameter("accept");
        String province = req.getParameter("province");
        String city = req.getParameter("city");
        String area = req.getParameter("area");
        String address = req.getParameter("address");
        String telphone = req.getParameter("telphone");
        String state = req.getParameter("type");
        HttpSession session = req.getSession();
        User u = (User) session.getAttribute("USER");
        Integer sfid = null;
        Integer sid = null;
        Integer qid = null;
        JSONObject jsonObject = new JSONObject();
        PrintWriter writer = resp.getWriter();
        if (province != null) {
            sfid = Integer.parseInt(province);
        }
        if (province != null) {
            sid = Integer.parseInt(city);
        }
        if (province != null) {
            qid = Integer.parseInt(area);
        }
        try {
            addressService.updateAddress(accept, sfid, sid, qid, address, telphone, Integer.parseInt(state), u.getId(),Integer.parseInt(id));
            jsonObject.put("msg", "ok");
        } catch (AddressDefaultNumMuchException e) {
            e.printStackTrace();
            jsonObject.put("msg", "至少需要一个默认地址");
        } catch (ServiceException e) {
            e.printStackTrace();
            jsonObject.put("msg", "系统维护中，请稍后再试");
        }
        writer.print(jsonObject);
        writer.close();
    }

    private void doDel(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String aid = req.getParameter("id");
        PrintWriter writer = resp.getWriter();
        HttpSession session = req.getSession();
        User u = (User) session.getAttribute("USER");
        JSONObject jsonObject = new JSONObject();

        try {
            addressService.delAddress(Integer.parseInt(aid), u.getId());
            jsonObject.put("msg", "ok");
        } catch (AddressDefaultNumMuchException e) {
            e.printStackTrace();
            jsonObject.put("msg", "至少需要一个默认地址");
        } catch (ServiceException e) {
            e.printStackTrace();
            jsonObject.put("msg", "系统维护中，请稍后再试");
        }
        writer.print(jsonObject);
        writer.close();
    }

    private void doSetDefault(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String aid = req.getParameter("id");
        PrintWriter writer = resp.getWriter();
        HttpSession session = req.getSession();
        User u = (User) session.getAttribute("USER");
        JSONObject jsonObject = new JSONObject();
        try {
            addressService.setDefaultAddress(u.getId(), Integer.parseInt(aid));
            jsonObject.put("msg", "ok");
        } catch (AddressDefaultNumMuchException e) {
            e.printStackTrace();
            jsonObject.put("msg", "最多只能拥有一个默认地址");
        } catch (ServiceException e) {
            e.printStackTrace();
            jsonObject.put("msg", "系统维护中，请稍后再试");
        }

        writer.print(jsonObject);
        writer.close();
    }

    private void doInitupdate(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String aid = req.getParameter("id");
        PrintWriter writer = resp.getWriter();
        Address address = addressService.getAddress(Integer.parseInt(aid), null);
        String jsonObject = JSON.toJSONString(address);
        writer.print(jsonObject);
        writer.close();
    }

    private void doAdd(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String accept = req.getParameter("accept");
        String province = req.getParameter("province");
        String city = req.getParameter("city");
        String area = req.getParameter("area");
        String address = req.getParameter("address");
        String telphone = req.getParameter("telphone");
        String state = req.getParameter("type");
        HttpSession session = req.getSession();
        User u = (User) session.getAttribute("USER");
        Integer sfid = null;
        Integer sid = null;
        Integer qid = null;
        JSONObject jsonObject = new JSONObject();
        PrintWriter writer = resp.getWriter();
        if (province != null) {
            sfid = Integer.parseInt(province);
        }
        if (province != null) {
            sid = Integer.parseInt(city);
        }
        if (province != null) {
            qid = Integer.parseInt(area);
        }
        try {
            addressService.addAddress(accept, sfid, sid, qid, address, telphone, Integer.parseInt(state), u.getId());
            jsonObject.put("msg", "ok");
        } catch (AddressNumMuchException e) {
            e.printStackTrace();
            jsonObject.put("msg", "最多只能拥有" + MallDefaultConfig.MAX_ADDRESS + "个收货地址");
        } catch (AddressDefaultNumMuchException e) {
            e.printStackTrace();
            jsonObject.put("msg", "最多只能拥有一个默认地址");
        } catch (ServiceException e) {
            e.printStackTrace();
            jsonObject.put("msg", "系统维护中，请稍后再试");
        }
        writer.print(jsonObject);
        writer.close();
    }

    private void doProvince(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String pid = req.getParameter("pid");
        List<Region> regionList = null;
        if (pid == null || pid.isEmpty()) {
            regionList = regionService.getRegionByPidList(null);
        } else {
            regionList = regionService.getRegionByPidList(Integer.parseInt(pid));
        }

        String jsonString = JSON.toJSONString(regionList);
        PrintWriter writer = resp.getWriter();
        writer.print(jsonString);
        writer.close();
    }

    /**
     * 查询有效地址
     *
     * @param req
     * @param resp
     */
    private void doList(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession();
        User u = (User) session.getAttribute("USER");
        List<Address> addressList = null;
        try {
            addressList = addressService.getAllAddress(u.getId());
        } catch (ServiceException e) {
            e.printStackTrace();

        }

        String addressJson = JSON.toJSONString(addressList);
        PrintWriter writer = resp.getWriter();
        writer.print(addressJson);
        writer.close();
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
